package com.pine.common.threadpool.core;

import com.pine.common.threadpool.ThreadPoolConstant;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 动态线程池管理器
 *
 * @author pine manage
 * @since 2024-08-28
 */
@Slf4j
public class DynamicThreadPoolManager {

    private static final Map<String, ThreadPoolExecutor> THREAD_POOL_EXECUTOR_MAP = new HashMap<>(16);

    /**
     * 获取线程池
     *
     * @param businessCode 业务编码
     * @param businessKey  业务key
     * @return 线程池实例
     * @throws RuntimeException 运行时异常
     */
    public static ThreadPoolExecutor getThreadPoolExecutor(String businessCode, String businessKey) throws RuntimeException {
        Objects.requireNonNull(businessCode, "businessCode is empty");
        Objects.requireNonNull(businessKey, "businessKey is empty");
        String threadPoolName = ThreadPoolConstant.THREAD_POOL_NAME_FORMAT.formatted(businessCode, businessKey);

        if (THREAD_POOL_EXECUTOR_MAP.containsKey(threadPoolName)) {
            return THREAD_POOL_EXECUTOR_MAP.get(threadPoolName);
        } else {
            ThreadPoolExecutor threadPoolExecutor = ThreadPoolExecutorFactory.createThreadPoolExecutor(businessCode, businessKey);
            THREAD_POOL_EXECUTOR_MAP.put(threadPoolName, threadPoolExecutor);
            return threadPoolExecutor;
        }
    }

    static Map<String, ThreadPoolExecutor> getThreadPoolExecutorMap() {
        return THREAD_POOL_EXECUTOR_MAP;
    }
}
